package com.meteor.controller;

import com.meteor.pojo.Shop;
import com.meteor.pojo.User;
import com.meteor.service.BookService;
import com.meteor.service.ShopService;
import com.meteor.pojo.BookDto;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/shop")
public class ShopController {

    @Resource
    private ShopService shopService;

    @Resource
    private BookService bookService;


    // 查询所有购物车的书
    @GetMapping("/selectAllShop")
    public String selectAllShop(Model model,HttpSession session) {
        User user = (User)session.getAttribute("user");

        List<Shop> shops = shopService.selectAllShop();
        ArrayList<Shop> list = new ArrayList<>();
        int size = shops.size();

        for (int i = 0; i < size; i++) {
            if(shops.get(i).getUserId() == user.getId()) {
                list.add(shops.get(i));
            }
        }
        if(list.size() != 0) {
            int[] array1 = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                array1[i] = list.get(i).getBookId();
            }
            List<BookDto> books = bookService.selectBookByBookIds(array1);
            model.addAttribute("books", books);
        }
        return "front/shop";
    }

    // 根据bookID删除购物车中的书
    @GetMapping("/delete/{bookId}")
    public String deleteByBookId(@PathVariable Integer bookId) {
        int i = shopService.deleteByBookId(bookId);
        return "forward:/shop/selectAllShop";
    }

    // 根据bookId修改购物车商品数量
    @GetMapping("/updateCount")
    public String updateCountByBookId(Shop shop) {
        int count = shopService.updateCountByBookId(shop);
        return "forward:/shop/selectAllShop";
    }

    // 根据传来的bookId们，将其价格汇总
    @GetMapping("/goShop")
    public String goShop(String[] books, HttpSession session) { //bookId=2&bookId=3&
        if(books != null) {
            String[] split = Arrays.toString(books).split("&");
            ArrayList<String> array = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                array.add((split[i].substring(split[i].length() - 1)));
            }

            Integer[] arr = new Integer[array.size() - 1];
            for (int i = 0; i < array.size() - 1; i++) {
                arr[i] = Integer.parseInt(array.get(i));
            }
            Integer price = bookService.selectPrice(arr);
            session.setAttribute("arr", arr);
            session.setAttribute("price", price);
        }
        return "front/pay";
    }
}














